<template>
  <a-modal
      :width="500"
      :visible="visible"
      title="新增招商人员"
      @cancel="onClose"
      @ok="onSubmit"
      ok-text="确定"
      :destroyOnClose="true"
      :confirmLoading="loading"
  >
    <a-spin :spinning="spinning">
      <a-form>
        <a-row :wrap="true" :gutter="12">
          <a-col :span="24" v-if="fromType == 'team'">
            <a-form-item label="当前团队">
              <span>{{ teamName }}</span>
            </a-form-item>
          </a-col>
          <a-col :span="24" v-if="fromType == 'person'">
            <a-form-item label="选择团队" v-bind="validateInfos.team_id">
              <a-select
                  v-model:value="formData.team_id"
                  :options="teamOptions"
                  placeholder="请选择招商团队"
                  :allowClear="true"
                  style="width: 100%"
                  @change="teamChange"
              >
                <template #dropdownRender="{ menuNode: menu }">
                  <v-nodes :vnodes="menu"/>
                  <a-divider style="margin: 4px 0"/>
                  <div
                      style="
                            padding: 4px 8px;
                            cursor: pointer;
                            text-align: center;
                            color: #2681f3;
                          "
                      @mousedown="(e) => e.preventDefault()"
                      @click="addTeamVisible = true"
                  >
                    添加
                  </div>
                </template>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="人员信息" v-bind="validateInfos.team_user">
              <a-row class="user-tag" align="middle">
                <a-tag
                    closable
                    v-for="(user, index) of idList.user"
                    :key="user.uid"
                    @close="idListRemove('user', index, user.uid)"
                    style="margin: 5px 10px 5px 0"
                >
                  <a-avatar
                      :src="user.avatar"
                      style="color: #fff; background-color: #2681f3"
                  >
                    <template #icon>
                      <UserOutlined/>
                    </template>
                  </a-avatar>
                  <span class="ml-10"> {{ user.realname }} </span>
                </a-tag>
                <a-button type="primary" ghost @click="chooseMember"
                >添加
                </a-button
                >
              </a-row>
            </a-form-item>
          </a-col>

        </a-row>
      </a-form>
    </a-spin>


    <!-- 选择人员 -->
    <ChooseOrgMember
        :visible="chooseMemberVisible"
        :getDetail="true"
        :deptDisabled="true"
        :uids="selectedUids"
        setUids="uncheck"
        @request="$utils.commonRequest"
        @close="closeChooseMemberModal"
        @success="handleMemberSelect"
        :checkedList="idList"
    />

    <!--  新增团队  -->
    <AddBusinessTeam
        :visible="addTeamVisible"
        :villageOptions="villageOptions"
        @cancelAdd="addTeamVisible = false"
        @success="addTeamSuccess"
    />
  </a-modal>

</template>
<script>
import {defineComponent, reactive, toRefs, computed, watch} from "vue";
import {Form, message} from "ant-design-vue";
import store from "../../../../store";
import request from "../../../../common/utils/request";
import {UserOutlined} from "@ant-design/icons-vue";

const useForm = Form.useForm;
import {ChooseOrgMember} from "bl-common-vue3";
import _ from "lodash";
import AddBusinessTeam from "@/views/village/BusinessManage/modules/AddBusinessTeam.vue";

export default defineComponent({
  name: "AddTeamPersonnel",
  props: {
    id: {
      type: [Number, String],
      default: 0,
    },
    visible: {
      type: Boolean,
      default: false,
    },
    teamName: {
      type: String,
      default: '',
    },
    // 默认来自团队
    fromType: {
      type: String,
      default: 'team',
    },
    villageOptions: {
      type: Array,
      default: () => [],
    },
  },
  components: {
    VNodes: (_, {attrs}) => {
      return attrs.vnodes;
    },
    AddBusinessTeam,
    UserOutlined,
    ChooseOrgMember
  },
  setup(props, {emit}) {
    const state = reactive({
      idList: {},
      chooseMemberVisible: false,
      loading: false,
      teamOptions: [],
      spinning: false,
      ruleRef: {
        team_user: [{required: true, message: "必选"}],
        team_id: [{required: false, message: "必选"}],
      },
      addTeamVisible: false,
      selectedUids: [],
    });

    const formData = reactive({
      team_user: [],
      team_id: undefined, // 选择团队id
    });

    const {resetFields, validate, validateInfos} = useForm(formData, state.ruleRef);

    const onSubmit = () => {
      validate().then(() => {
        let params = {};
        if (props.fromType == 'team') {
          params.team_id = props.id;
        }
        for (let key in formData) {
          if (formData[key] || formData[key] === 0) {
            params[key] = formData[key];
          }
        }
        state.loading = true;
        request.post("/org", "/business/customerTeam/setTeamUser", params).then((res) => {
          message.success(res.msg || "添加成功!");
          emit("success");
        }).finally(() => {
          state.loading = false;
        });
      });
    };


    const idListRemove = (type = "user", index, uid) => {
      state.idList[type].splice(index, 1);
      formData.team_user = formData.team_user.filter(
          (item) => item !== uid
      );
    };

    const chooseMember = () => {
      state.chooseMemberVisible = true;
    };


    const closeChooseMemberModal = () => {
      state.chooseMemberVisible = false;
    };

    const handleMemberSelect = (data) => {
      state.idList = data;
      closeChooseMemberModal();
      formData.team_user = [];
      formData.team_user = data.user.map((item) => item.uid);
    };

    const getTeamList = () => {
      return new Promise((resolve) => {
        state.spinning = true;
        request.get("/org", "/business/customerTeam/teamIndex", {}).then((res) => {
          let teamList = res?.data || [];
          state.teamOptions = teamList.map((v) => {
            return {
              label: v.name,
              value: v.id,
            }
          })
          resolve();
        }).finally(() => {
          state.spinning = false;
        });
      });
    };

    const teamChange = () => {
      const params = {
        team_id: formData.team_id
      }
      request.get("/org", "/business/customerTeam/getNotSelectTeamUser", params).then(res => {
        state.selectedUids = res.data.map(item => {
          return item.uid
        });
      })
    }

    const onClose = () => {
      emit("handleCancel");
    };

    const init = () => {
      state.ruleRef.team_id[0].required = props.fromType !== 'team';
      if (props.fromType == 'team') return;
      getTeamList();
    };

    const addTeamSuccess = () => {
      getTeamList();
      state.addTeamVisible = false;
    };


    const reset = () => {
      state.idList = {};
      state.loading = false;
      state.teamOptions = [];
      state.spinning = false;
    }


    watch(
        () => props.visible,
        (val) => {
          if (val) {
            init();
          } else {
            resetFields();
            reset();
          }
        }
    );

    return {
      ...toRefs(state),
      formData,
      validateInfos,
      onClose,
      onSubmit,
      idListRemove,
      chooseMember,
      closeChooseMemberModal,
      handleMemberSelect,
      addTeamSuccess,
      teamChange,

    };
  },
});
</script>

<style lang="less" scoped>
p {
  &:last-of-type {
    margin-bottom: 0;
  }
}

.user-tag :deep(.ant-tag) {
  border-radius: 20px !important;
  padding: 0 12px 0 0 !important;
  background: #f1f1f1;
  border: none;
}
</style>
